package com.cn.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.cn.domain.Cart;
import com.cn.domain.Order;
import com.cn.domain.User;
import com.cn.service.CartService;
import com.cn.service.OrderService;
import com.cn.service.impl.CartServiceImpl;
import com.cn.service.impl.OrderServiceImpl;

@WebServlet("/OrderServlet")
public class OrderServlet extends HttpServlet {
	
	private OrderService orderService=new OrderServiceImpl();
	
	private CartService cartService=new CartServiceImpl();
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		this.doGet(req, resp);
	}

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		System.out.println("dsdfsds..order by ding");
		//生成订单
		//1:插入数据到订单表中,并且也要插入到订单详情表中
		//2:当插入的同时害得进行删除购物车并且删除数据库中的数据（使用用户ID删除购物产品）
		//这里开始进行插入到数据库
		User user=(User)req.getSession().getAttribute("user");
		if(user==null) {
			//没有登录直接跳转到登陆界面
			req.getRequestDispatcher("/login.jsp").forward(req, resp);
			return;
		}
		
		//生成订单,接着显示
		//查询所有购物车里的信息进行生成订单表,这个数据用于显示订单
		List<Cart> cartList=cartService.queryAllCart(user.getHu_user_id());
		long sumPrice=0;
		//计算总金额
		for(Cart c:cartList) {
			sumPrice+=c.getQuantity()*c.getProduct().getHp_price();
		}
		
		if(cartList!=null&&(cartList.size()==0)) {
			//跳转到d首页继续进行购买
			req.getRequestDispatcher("/index.jsp").forward(req, resp);
			return;
		}
		
		//显示完之后就需要进行更新数据库	
		Cart cart=new Cart();
		cart.setUserid(user.getHu_user_id());
		//开始插入订单+
		if(orderService.addOrder(cart)>0) {
			System.out.println("生产等订单成功!");
		}
		
		//取出订单的ID和创建时间
		Order order=orderService.queryCartByTime();
		//开始orderView
		req.getSession().setAttribute("orderView",cartList);
		//总价钱
		req.getSession().setAttribute("totalPrice",sumPrice);
		//订单ID
		req.getSession().setAttribute("orderId",order.getHo_id());
		//订单创建时间
		req.getSession().setAttribute("time",order.getHo_create_time());
		req.getRequestDispatcher("/reg-result2.jsp").forward(req, resp);
	}
}
